//
//  ChatInputViewController.m
//  HDMainWindow
//
//  Created by apple on 2017/5/3.
//  Copyright © 2017年 com.devin.definesys. All rights reserved.
//

#import "ChatInputViewController.h"

#import "DMMessageBaseCell.h"
#import "DMMessageTextCell.h"
#import "DMMessageCellManager.h"

#import "DMMessageTextModel.h"
#import "DMMessageTimeModel.h"

#import "LLChatInputView.h"
#import "LLUtils.h"

#import "DMMessageImageModel.h"

#define BLACK_BAR_VIEW_TAG 1000
#define MAIN_BOTTOM_TABBAR_HEIGHT 50

@interface ChatInputViewController ()<UITableViewDelegate,UITableViewDataSource,LLChatInputDelegate, LLChatShareDelegate,LLMessageCellActionDelegate> {
    UITapGestureRecognizer *tapGesture;
    UITextField *textField;
    
    BOOL firstViewWillAppear;
    BOOL firstViewDidAppear;
    
    BOOL isChatControllerDidAppear;
    
    BOOL isPulling;
    BOOL isLoading;
}

//tableView
@property (weak, nonatomic) IBOutlet UITableView *tableView;

//下方功能块
@property (weak, nonatomic) IBOutlet LLChatInputView *chatInputView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewBottomConstraint;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *chatInputViewBottomConstraint;

@end

//
@implementation ChatInputViewController

#pragma 测试数据
- (void) setupModel {
    NSMutableArray *_modelArray = [NSMutableArray array];
    DMMessageBaseModel *model1 = [[DMMessageTimeModel alloc] init];
    model1.modelType = @"TIME";
    model1.fromMe = NO ;
    
    DMMessageTextModel *model2 = [[DMMessageTextModel alloc] init];
    model2.modelType = @"TEXT";
    model2.fromMe = YES ;
    model2.attrText = [[NSAttributedString alloc] initWithString:@"dsfafasdfsfsfsfdsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaafdsafasdfsafsfsadfasfas"];
    
    DMMessageTextModel *model3 = [[DMMessageTextModel alloc] init];
    model3.modelType = @"TEXT";
    model3.fromMe = NO ;
    model3.attrText = [[NSAttributedString alloc] initWithString:@"aaaaaaaaaaaaaaaaaaa"];
    
    DMMessageImageModel *model4 = [[DMMessageImageModel alloc] init];
    model4.modelType = @"IMAGE";
    model4.fromMe = YES ;
    model4.fileLocalPath = [[NSBundle mainBundle] pathForResource:@"imageDownloadFail" ofType:@"png"];
    
    [_modelArray addObject:model1];
    [_modelArray addObject:model2];
    [_modelArray addObject:model3];
    [_modelArray addObject:model2];
    [_modelArray addObject:model4];
    [_modelArray addObject:model4];
    [_modelArray addObject:model4];
    [_modelArray addObject:model4];
    [_modelArray addObject:model4];

    
    self.chatInputView.delegate = self ;
    
    _converstaionModel = [[DMConverstaionModel alloc] init];
    _converstaionModel.allMessageModels = _modelArray ;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO ;
    
    self.tableView.delegate = self ;
    self.tableView.dataSource = self ;
    
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    
    tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandler:)];
    tapGesture.numberOfTapsRequired = 1;
    tapGesture.numberOfTouchesRequired = 1;
    [self.tableView addGestureRecognizer:tapGesture];
    
    [self setupModel];
    
    self.chatInputView.delegate = self;
    [self refreshChatControllerForReuse];

    [self.view layoutIfNeeded];
    // Do any additional setup after loading the view.
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _converstaionModel.allMessageModels.count ;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [UIView setAnimationsEnabled:NO];

    DMMessageBaseCell *cell = [[DMMessageCellManager sharedInstance] cellForBaseModel:_converstaionModel.allMessageModels[indexPath.row]];
    
    cell.delegate = self;
    
    [UIView setAnimationsEnabled:YES];
    
    return cell ;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [_converstaionModel.allMessageModels[indexPath.row] cellHeight] ;
}

- (void)updateViewConstraints {
    [super updateViewConstraints];
}

#pragma mark - 处理键盘事件
- (void)updateKeyboard:(LLKeyboardShowHideInfo)keyboardInfo {
    CGFloat constant = keyboardInfo.toKeyboardType == kLLKeyboardTypeNone ? 0 :
    keyboardInfo.keyboardHeight;
    
    if (keyboardInfo.duration == 0) {
        [UIView setAnimationsEnabled:NO];
    }
    
    BOOL needScrollToBottom = ((self.chatInputViewBottomConstraint.constant == 0) && (constant > 0));
    [UIView animateWithDuration:keyboardInfo.duration
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState |
     keyboardInfo.curve
                     animations:^() {
                         self.chatInputViewBottomConstraint.constant = -constant;
                         [self.view layoutIfNeeded];
                         
//                         self.tableView.contentInset = UIEdgeInsetsMake(constant + CGRectGetHeight(self.chatInputView.frame) + 50, 0, 0, 0);
//                         self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
                         
                     }
                     completion: nil];
    
    if (needScrollToBottom) {
        [self scrollToBottom:keyboardInfo.duration > 0];
    }
    
    if (keyboardInfo.duration == 0) {
        [UIView setAnimationsEnabled:YES];
    }
}

- (void)scrollToBottom:(BOOL)animated {
//    if (self.dataSource.count == 0)
//        return;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_converstaionModel.allMessageModels.count - 1 inSection:0];
    //    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if (cell) {
        CGFloat offsetY = self.tableView.contentSize.height + self.tableView.contentInset.bottom - CGRectGetHeight(self.tableView.frame);
        if (offsetY < -self.tableView.contentInset.top)
            offsetY = -self.tableView.contentInset.top;
        [self.tableView setContentOffset:CGPointMake(0, offsetY) animated:animated];
    }else {
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
    
}

- (void)tapHandler:(UITapGestureRecognizer *)tap {
    [self.chatInputView dismissKeyboard];
    
//    if (_sightController) {
//        [self sightCapatureControllerDidCancel:_sightController];
//    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (!firstViewWillAppear) {
        
        firstViewWillAppear = YES;
        
//        lastedMessageModel = [self.conversationModel.allMessageModels lastObject];
//        if (self.conversationModel.draft.length > 0) {
//        }
        [self.chatInputView activateKeyboard];
    }
    
//    [LLChatManager sharedManager].messageListDelegate = self;
//    navigationBarTranslucent = self.navigationController.navigationBar.translucent;
    self.navigationController.navigationBar.translucent = NO;
    
    UIView *blackView = [self.view viewWithTag:BLACK_BAR_VIEW_TAG];
    if (self.navigationController.navigationBar.subviews[0].alpha == 0 && !blackView) {
        blackView = [[UIView alloc] initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, 64)];
        blackView.backgroundColor = [UIColor blackColor];
        [self.view addSubview:blackView];
    }
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (!firstViewDidAppear) {
        firstViewDidAppear = YES;
        
        [self.chatInputView prepareKeyboardWhenConversationDidBegan];
        
        
//        [[LLChatManager sharedManager] markAllMessagesAsRead:self.conversationModel];
    }
    [self.chatInputView registerKeyboardNotification];
    
    self.chatInputView.delegate = self;
    
    isChatControllerDidAppear = YES;
//    _voiceTipView.hidden = NO;
    
    self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan= NO;
    
    self.navigationController.navigationBar.subviews[0].alpha = 1;
    UIView *blackView = [self.view viewWithTag:BLACK_BAR_VIEW_TAG];
    [blackView removeFromSuperview];
    
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    //当会话隐藏时，取消键盘事件和代理
    [self.chatInputView unregisterKeyboardNotification];
    self.chatInputView.delegate = nil;
    
//    self.navigationController.navigationBar.translucent = navigationBarTranslucent;
//    _voiceTipView.hidden = YES;
    //后退
    if (![self.navigationController.childViewControllers containsObject:self]) {
//        //如果更了新消息，或者保留草稿，则把当前会话在会话列表置顶
        
        //后退时停止tableview滚动
        [self.tableView setContentOffset:self.tableView.contentOffset animated:NO];
        
        //FIXME:会话退出时，强制输入框取消FirstResponder,这样下次打开会话时，就不会
        //自动成为FirstResponder了，目前没有发现更好的解决方法
        //仅仅设置TextViewEditable = NO;下次会话不会自动弹键盘，但进入会话会卡顿一下
        if (self.chatInputView.keyboardType == kLLKeyboardTypeDefault) {
            if (!textField) {
                textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
            }
            [self.view addSubview:textField];
            textField.hidden = YES;
            [textField becomeFirstResponder];
            [self.chatInputView setTextViewEditable:NO];
        }
    }
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan = YES;
    
    if (![self.navigationController.childViewControllers containsObject:self]) {
        //清理下拉刷新
//        UIActivityIndicatorView *indicator = self.refreshView.subviews[0];
//        [indicator stopAnimating];
        self.tableView.tableHeaderView = nil;
        isLoading = NO;
        isPulling = NO;
        
//        //停止播放录音
//        [[LLAudioManager sharedManager] stopPlaying];
//        [[LLDeviceManager sharedManager] disableProximitySensor];
//        [LLDeviceManager sharedManager].delegate = nil;
//        
        //清理Model和缓存
//        [self cleanMessageModelWhenExit];
//        [[LLMessageCacheManager sharedManager] cleanCacheWhenConversationExit:self.conversationModel];
        
//        [self.conversationModel.allMessageModels removeAllObjects];
//        [self.dataSource removeAllObjects];
        [self.tableView reloadData];
        
        //取消消息代理
//        [LLChatManager sharedManager].messageListDelegate = nil;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        
        //清理输入键盘
//        self.conversationModel.draft = self.chatInputView.currentInputText;
//        [self.conversationModel saveDraftToDB];
        [self.chatInputView dismissKeyboardWhenConversationEnd];
        
        //清除小视频
//        [self removeSightController];
        
        //其他
//        [_voiceTipView removeFromSuperview];
        [textField removeFromSuperview];
        isChatControllerDidAppear = NO;
        firstViewDidAppear = NO;
        firstViewWillAppear = NO;
    }
    
}

- (void)refreshChatControllerForReuse {
//    self.navigationItem.title = self.conversationModel.nickName;
    
//    [self registerApplicationNotification];
//    [self registerChatManagerNotification];
    
    if (self.converstaionModel.updateType == kLLMessageListUpdateTypeLoadMore) {
        if (!self.tableView.tableHeaderView) {
//            self.tableView.tableHeaderView = self.refreshView;
        }
    }else if (self.converstaionModel.updateType == kLLMessageListUpdateTypeLoadMoreComplete) {
        self.tableView.tableHeaderView = nil;
    }
    
    self.chatInputView.draft = self.converstaionModel.draft;
    self.chatInputView.delegate = self;
    [self.chatInputView prepareKeyboardWhenConversationWillBegin];
    
    if (self.converstaionModel.draft.length == 0 ) {
        self.chatInputViewBottomConstraint.constant = 0;
    }
    
    [self.view layoutIfNeeded];
    
    self.tableView.contentInset = UIEdgeInsetsMake(CGRectGetHeight(self.chatInputView.frame) - MAIN_BOTTOM_TABBAR_HEIGHT + self.chatInputViewBottomConstraint.constant, 0, 0, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
//
//    self.dataSource = [self processData:self.conversationModel];
    [self.tableView reloadData];
    
    [self scrollToBottom:NO];
    
}

- (void)cellWithTagDidTapped:(NSInteger)tag {
    
}

- (void)sendTextMessage:(NSString *)text {
    
}

- (void)sendGifMessage:(LLEmotionModel *)model {
    
}

- (void)textViewDidChange:(UITextView *)textView {
    
}


#pragma mark - 录音

- (void)voiceRecordingShouldStart {
    
}

- (void)voiceRecordingShouldCancel {
    
}

- (void)voicRecordingShouldFinish {
    
}

- (void)voiceRecordingDidDraginside {
    
}

- (void)voiceRecordingDidDragoutside {
    
}

- (void)voiceRecordingTooShort {
    
}

#pragma mark - 菜单

- (void)willShowMenuForCell:(DMMessageBaseCell *)cell {
}

- (void)didShowMenuForCell:(DMMessageBaseCell *)cell {
//    [self.chatInputView dismissKeyboard];
}

- (void)willHideMenuForCell:(DMMessageBaseCell *)cell {
    
}

- (void)didHideMenuForCell:(DMMessageBaseCell *)cell {
    self.chatInputView.chatInputTextView.targetCell = nil;
}

- (UIResponder *)currentFirstResponderIfNeedRetain {
    UITextView *textView = self.chatInputView.chatInputTextView;
    
    return textView.isFirstResponder ? textView : nil;
}

@end
